'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Receipt, FileSpreadsheet, PieChart as PieChartIcon } from 'lucide-react';
import { formatMoney, getApiUrl } from '@/lib/utils';
import {
  PieChart,
  Pie,
  Cell,
  ResponsiveContainer,
  Tooltip,
  Legend,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
} from 'recharts';

const expenseTypeMap = {
  material: '材料费',
  labor: '人工费',
  equipment: '设备费',
  other: '其他费用'
} as const;

const COLORS = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042'];

interface SiteExpenses {
  siteName: string;
  material: number;
  labor: number;
  equipment: number;
  other: number;
}

interface ExpenseTypeData {
  pieData: Array<{ name: string; value: number }>;
  barData: SiteExpenses[];
  expensesByType: Record<string, number>;
  totalExpenses: number;
}

function ExpenseTypeAnalysis({ data }: { data: ExpenseTypeData }) {
  return (
    <div className="space-y-6">
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        {Object.entries(data.expensesByType).map(([type, amount]) => (
          <Card key={type}>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">
                {expenseTypeMap[type as keyof typeof expenseTypeMap]}
              </CardTitle>
              <Receipt className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{formatMoney(amount)}</div>
              <p className="text-xs text-muted-foreground">
                占比 {((amount / data.totalExpenses) * 100).toFixed(1)}%
              </p>
            </CardContent>
          </Card>
        ))}
      </div>

      <div className="grid gap-4 md:grid-cols-2">
        <Card>
          <CardHeader>
            <CardTitle>支出类型分布</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="h-[400px]">
              <ResponsiveContainer width="100%" height="100%">
                <PieChart>
                  <Pie
                    data={data.pieData}
                    cx="50%"
                    cy="50%"
                    labelLine={false}
                    label={({ name, percent }) => `${name} ${(percent * 100).toFixed(1)}%`}
                    outerRadius={120}
                    fill="#8884d8"
                    dataKey="value"
                  >
                    {data.pieData.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                    ))}
                  </Pie>
                  <Tooltip
                    formatter={(value: number) => formatMoney(value)}
                  />
                </PieChart>
              </ResponsiveContainer>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>各工地支出类型对比</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="h-[400px]">
              <ResponsiveContainer width="100%" height="100%">
                <BarChart
                  data={data.barData}
                  margin={{
                    top: 20,
                    right: 30,
                    left: 20,
                    bottom: 5,
                  }}
                >
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="siteName" />
                  <YAxis />
                  <Tooltip formatter={(value: number) => formatMoney(value)} />
                  <Legend />
                  <Bar dataKey="material" name="材料费" fill={COLORS[0]} stackId="a" />
                  <Bar dataKey="labor" name="人工费" fill={COLORS[1]} stackId="a" />
                  <Bar dataKey="equipment" name="设备费" fill={COLORS[2]} stackId="a" />
                  <Bar dataKey="other" name="其他费用" fill={COLORS[3]} stackId="a" />
                </BarChart>
              </ResponsiveContainer>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}

export default function ExpenseTypeReportPage() {
  const [data, setData] = useState<ExpenseTypeData | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    async function loadData() {
      try {
        const response = await fetch(getApiUrl('reports/by-type'));
        if (!response.ok) throw new Error('加载数据失败');
        const data = await response.json();
        setData(data);
      } catch (error) {
        console.error('加载数据失败:', error);
      } finally {
        setIsLoading(false);
      }
    }
    loadData();
  }, []);

  return (
    <main className="container mx-auto p-4 space-y-4">
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">支出类型分析</h1>
          <p className="text-muted-foreground">
            查看各类支出的分布情况和工地间的对比
          </p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" asChild>
            <Link href="/reports">
              <PieChartIcon className="mr-2 h-4 w-4" />
              总览报表
            </Link>
          </Button>
          <Button>
            <FileSpreadsheet className="mr-2 h-4 w-4" />
            导出报表
          </Button>
        </div>
      </div>

      {isLoading ? (
        <div>加载中...</div>
      ) : data ? (
        <ExpenseTypeAnalysis data={data} />
      ) : (
        <div>加载失败</div>
      )}
    </main>
  );
} 